package com.foreknow.elm.dao.Impl;

import com.foreknow.elm.dao.UserDao;
import com.foreknow.elm.po.User;
import com.foreknow.elm.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    private Connection conn;
    private PreparedStatement pst;
    private ResultSet rs;
    @Override
    public User getUserByIdByPass(String userId, String password) throws SQLException {
        User user=new User();
        try {
            String sql="select * from user where userId=? and password=?";
            conn= DBUtil.getConnection();
            pst=conn.prepareStatement(sql);
            pst.setString(1,userId);
            pst.setString(2,password);
            rs=pst.executeQuery();
            while (rs.next()){
                user.setUserId(rs.getString("UserId"));
                user.setPassword(rs.getString("Password"));
                user.setUserName(rs.getString("UserName"));
                user.setUserSex(rs.getInt("UserSex"));
                user.setUserImg(rs.getString("UserImg"));
                user.setDelTag(rs.getInt("DelTag"));
            }
        }finally {
            DBUtil.close(pst);
        }

        return user;
    }

    @Override
    public int getUserById(String userId) throws SQLException {
        int i=0;
        try {
            String sql="select count(*) as Num from user where userId=?";
            conn= DBUtil.getConnection();
            pst= conn.prepareStatement(sql);
            pst.setString(1,userId);
            rs= pst.executeQuery();
            if (rs.next()){
                i=rs.getInt("Num");
            }
        }finally {
            DBUtil.close(pst);
        }
        return  i;
    }

    @Override
    public int saveUser(String userId, String password, String userName, Integer userSex) throws SQLException {
        int i=0;
        try {
            String sql="insert into user(userId,password,userName,userSex) value (?,?,?,?)";
            conn= DBUtil.getConnection();
            pst= conn.prepareStatement(sql);
            pst.setString(1,userId);
            pst.setString(2,password);
            pst.setString(3,userName);
            pst.setInt(4,userSex);
            i=pst.executeUpdate();
        }finally {
            DBUtil.close(pst);
        }
        return i;

    }

    public static void main(String[] args) throws SQLException {
        UserDao userDao=new UserDaoImpl();

//        System.out.println(userDao.saveUser("12345","132","TOM",1));

//        int i=userDao.getUserById("12345671111");
//        System.out.println(i);

//        try {
            User user=userDao.getUserByIdByPass("12345671111","123");
            System.out.println(user.getUserName());
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }
    }
}
